import {Menu, MenuProps} from "antd";
import {useEffect, useState} from "react";
import {MailOutlined} from "@ant-design/icons";
import {tree} from "./service";

type MenuItem = Required<MenuProps>['items'][number];

export default ()=>{
  const [menuList, setMenuList] = useState<MenuItem[]>([]);


  const renderMenuItem = (list:Record<string, any>[]):MenuItem[] =>{
    return list.map(item=>{
      if(item.children && item.children.length>0){
        return ({
          key: item.id,
          icon: <MailOutlined />,
          label: item.name,
          children: renderMenuItem(item.children),
        })
      }
      return {
        key: item.id,
        icon: <MailOutlined />,
        label: item.name,
      }
    })
  }

  useEffect(() => {
    tree({}).then(result=>{
      setMenuList(renderMenuItem(result.data));
    });
  }, []);

  const [stateOpenKeys, setStateOpenKeys] = useState<string[]>([]);

  const onOpenChange: MenuProps['onOpenChange'] = (openKeys) => {
    const currentOpenKey = openKeys.find((key) => stateOpenKeys.indexOf(key) === -1);
    setStateOpenKeys(currentOpenKey);
  };
  return (
    <Menu
      mode="inline"
      defaultSelectedKeys={['231']}
      openKeys={stateOpenKeys}
      onOpenChange={onOpenChange}
      items={menuList}
    />
  )
}
